import {Event} from "socket.io";
import { administratorClassroom, ADMINISTRATOR } from '../src/lib/Administrator'
import {RequestMethod} from "../src/lib/defines";
import { Classrooms } from '../src/lib/Classrooms'
import {errorMsg, okMsg} from "../src/utils/socket_message";
import {Members} from "../src/lib/Member";

export async function errorMiddleware (app, io) {
  const { socket } = app.locals;
  const { userId, username, userType } = socket.handshake.query;
  const adminClass = administratorClassroom.get(ADMINISTRATOR);
  const offerError = (message) => errorMsg(RequestMethod.offer, message)
  const JoinError = (msg) => errorMsg('joined', msg)
  console.log('------------------- adminMiddleware -----------------------')

  /**
   * 用户登录时
   * 查询未读通知，全部推送给对方。
   */
  socket.use(async (event: Event, next: (err?: Error) => void) => {
    const [name, params, cb] = event

    if (name === RequestMethod.offer) {
      // console.log('params: => ', params)
      const { member, room } = params
      const classroom = Classrooms.get(room.classId)
      if (!classroom) { // 房间不存在
        return cb && cb(offerError('room not find!'))
      }

      const __member = classroom.getMember(member.userId);
      if (!__member) { // 成员不存在
        return cb && cb(offerError('member not find!'))
      }
    }

    next()
  })
}
